package cn.nexd.app.collector.presenter.signin;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.nexd.app.collector.R;
import cn.nexd.app.collector.application.NexdApplication;
import cn.nexd.app.collector.presenter.db.NexdSqlOpenHelper;
import cn.nexd.app.collector.presenter.db.TableContract;
import cn.nexd.app.collector.presenter.network.HttpMethod;
import cn.nexd.app.collector.util.UrlUtil;
import cn.nexd.utils.framework.tools.MD5Util;


/**
 * Created by xun on 2016/7/31.
 */
public class SignInPresenter implements SignInContract.Presenter {
    @NonNull
    private final SignInContract.View signInView;

    public static final String EMAIL_MATCHES = "^[A-Za-z0-9]+@(nexdtech.com)+$";


    private static final String TAG = "SignInPresenter";
    private HttpMethod httpMethod;
    private NexdSqlOpenHelper databaseHelp;
    private Context mContext;

    public SignInPresenter(SignInContract.View signInView) {
        this.signInView = signInView;
        this.mContext = (Context) signInView;
        this.httpMethod = HttpMethod.getInstance(mContext);
        this.databaseHelp = NexdApplication.getInstance().getSqlHelper();
    }


    @Override
    public void init() {
        Cursor cursor = databaseHelp.selectCursor("select * from " + TableContract.Record.TABLE_NAME + " where " + TableContract.Record.COLUMN_NAME_ISREMEMBER + "=?", new String[]{1 + ""});
        if (cursor.moveToNext()) {
            String email = cursor.getString(cursor.getColumnIndex(TableContract.User.COLUMN_NAME_USEREMAIL));
            signInView.initIsRem(email);
        }
    }


    @Override
    public void loadUserInfo() {
        signInView.loading();
        Map<String, String> params = new HashMap<>();
        params.put("positionId", UrlUtil.POSITION_COLLECTOR);
        params.put("appKey", UrlUtil.APPKEY);
        StringBuffer userUrl = new StringBuffer(UrlUtil.BASE_IP);
        userUrl.append("user/v1.0/getUsers.do");
        httpMethod.execute(userUrl.toString(), new HttpMethod.OnRequestListener<JSONArray>() {
            @Override
            public void success(JSONArray data) throws JSONException {
                databaseHelp.deleteAll(TableContract.User.TABLE_NAME);
                for (int i = 0; i < data.length(); i++) {
                    JSONObject userJsonObject = data.getJSONObject(i);
                    String userName = userJsonObject.getString("userName");
                    String userEmail = userJsonObject.getString("userMail");
                    String userPassword = userJsonObject.getString("userPassword");
                    ContentValues values = new ContentValues();
                    values.put(TableContract.User.COLUMN_NAME_USEREMAIL, userEmail);
                    values.put(TableContract.User.COLUMN_NAME_USERPASSWORD, userPassword);
                    values.put(TableContract.User.COLUMN_NAME_USERNAME, userName);
                    databaseHelp.insert(values, TableContract.User.TABLE_NAME);
                }
                signInView.loadDataSuccess();
            }

            @Override
            public void requestError(String msg) {
                signInView.showToast(msg);
                signInView.loadDataFail();
            }

            @Override
            public void networkError(String msg) {
                signInView.printLog(msg);
                signInView.loadDataFail();
                signInView.showToast(mContext.getString(R.string.network_error));
            }
        }, params, "users");
    }

    @Override
    public boolean checkUser(String email, String pwd) {
        if (email.matches(EMAIL_MATCHES) && pwd.toString().length() >= 6) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void signIn(String email, String pwd, boolean isRem) {


//        Logger.debug(TAG, MD5Util.parseStrToMd5L32(pwd));
//        if (MD5Util.parseStrToMd5L32(pwd).equals("f3202f44165d073d0ed1cb0860c27a01")) {
//            signInView.signInSuccess(email);
//            if (isRem) {
//                SharedPreferences.Editor editor = mContext.getSharedPreferences("remember", Activity.MODE_PRIVATE).edit();
//                editor.putString("userName", email);
//                editor.apply();
//            }
//        } else {
//            signInView.signInPwdFail();
//        }

        Cursor cursor = databaseHelp.selectCursor("select * from user where " + TableContract.User.COLUMN_NAME_USEREMAIL + "=?", new String[]{email});
        if (cursor.getCount() > 0) {
            cursor.moveToNext();
            if (MD5Util.parseStrToMd5L32(pwd).equals(cursor.getString(cursor.getColumnIndex(TableContract.User.COLUMN_NAME_USERPASSWORD)))) {
                signInView.signInSuccess(cursor.getString(cursor.getColumnIndex(TableContract.User.COLUMN_NAME_USERNAME)));
                if (isRem) {
                    isRemember(email, true);
                }
            } else {
                signInView.signInPwdFail();
            }
        } else {
            signInView.signInUserNameFail();
        }
    }

    public void isRemember(String email, boolean isRem) {
        Cursor cursor = databaseHelp.selectCursor("select * from " + TableContract.User.TABLE_NAME + " where " + TableContract.User.COLUMN_NAME_USEREMAIL + "=?", new String[]{email});
        if (cursor.getCount() > 0) {
            databaseHelp.deleteAll(TableContract.Record.TABLE_NAME);
            ContentValues values = new ContentValues();
            values.put(TableContract.Record.COLUMN_NAME_USEREMAIL, email);
            values.put(TableContract.Record.COLUMN_NAME_ISREMEMBER, isRem);
            int count = databaseHelp.insert(values, TableContract.Record.TABLE_NAME);
            if (count > 0) {
                if (isRem) {
                    signInView.showToast("记住用户名成功");
                }
            }
        } else {
            signInView.rememberError();
        }
    }
}
